import { WebSocketServer,ConnectedSocket, MessageBody, SubscribeMessage, WebSocketGateway } from "@nestjs/websockets";
import * as WebSocket from 'ws';
import { Server } from 'ws';

@WebSocketGateway(3002)
export class WsStartGateway {
  @WebSocketServer()
  server: Server;

  private clients: Set<WebSocket> = new Set();

  afterInit(server: Server) {
    console.log('WebSocket 服务器初始化');
  }

  handleConnection(client: WebSocket) {
    console.log('客户端连接');
    this.clients.add(client);
  }

  handleDisconnect(client: WebSocket) {
    console.log('客户端断开连接');
    this.clients.delete(client);
  }

  @SubscribeMessage('hello')
  hello(@MessageBody() data: any): any {
    return {
      "event": "hello",
      "data": data,
      "msg": 'rustfisher.com'
    };
  }

  @SubscribeMessage('hello2')
  hello2(@MessageBody() data: any, @ConnectedSocket() client: WebSocket): any {
    console.log('收到消息:', data);
    const message = JSON.stringify({ event: 'hello2', data: data });
    console.log('message',message)
    if (client) {
      client.send(message);
    } else {
      // 广播消息给所有连接的客户端
      // 这需要您实现一个方法来管理所有连接的客户端
      this.broadcastMessage(message);
    }
    // return { event: 'hello2', data: data };
  }
  /**
   * 广播消息给所有连接的客户端
   * 
   * 这个方法的作用是:
   * 1. 遍历所有已连接的客户端(存储在this.clients集合中)
   * 2. 检查每个客户端的连接状态是否为OPEN(即连接是否处于活跃状态)
   * 3. 如果客户端连接是活跃的,就向该客户端发送指定的消息
   * 
   * 这样可以实现向所有在线的客户端同时发送相同的消息,
   * 适用于需要向多个客户端广播信息的场景,如系统通知、实时更新等。
   * 
   * @param message 要广播的消息内容
   */
  private broadcastMessage(message: string) {
    this.clients.forEach(client => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  }
}
